﻿var propertyDetails = {};
$(function () {
    var option = {
        titleID: "titleid",
        contentID: "contentdiv",
        currentClassName: "current",
        titleFun: getTitles,
        urlFun: getTabUrl,
        dataFun: getData,
        maodian: true,
        contentFun: null
    };
    //tab切换
    tabHelper(option);

    //表单验证
    agencyVerify.nonnegativeIntInput("input[isint=1]", true);
    agencyVerify.mobileInput("#addFollowForm", "#addFollowForm input[mobile=Mobile]", true, 'blur');
    agencyVerify.NoSame("#addFollowForm", "#addFollowForm input[mobile=Mobile]", "blur");
    agencyVerify.greaterThanEqualZero("input[greaterThan=-1]", true);
    agencyVerify.greaterThanEqualZero("#addFollowForm input[iszhengfu=1]", true);

    agencyVerify.notNullInput("#addFollowForm", "#addFollowForm input[name=ownerName]", true, "blur");

    agencyVerify.notdefaultSelect("#addFollowForm", "#addFollowForm :visible[name=GenderKeyId]", -1, "必须选择联系人称谓！", true);

    //售价涨浮显示
    $('#btnSalePriceChangeFlag').mouseover(function () {
        var currentel = $(this);
        var salePriceChangeFlag = $("#salePriceChangeFlag");
        salePriceChangeFlag.show();
        //salePriceChangeFlag.css("left", currentel.offset().left + 20);
        //salePriceChangeFlag.css("top", currentel.offset().top);
    }).mouseout(function () {
        $("#salePriceChangeFlag").hide();
    });
    //租价涨浮显示
    $('#btnRentPriceChangeFlag').mouseover(function () {
        var currentel = $(this);
        var rentPriceChangeFlag = $("#rentPriceChangeFlag");
        rentPriceChangeFlag.show();
        //rentPriceChangeFlag.css("left", currentel.offset().left + 20);
        //rentPriceChangeFlag.css("top", currentel.offset().top);
    }).mouseout(function () {
        $("#rentPriceChangeFlag").hide();
    });

    //房源贡献
    var propertyContributionArray = [{ '开盘': [] }, { '实勘': [] }, { '签约': [{ 'class': 'icon-fanqian-no2' }] }, { '钥匙': [{ 'class': 'keyno2' }] }, { '转介': [] }];

    $('#ulPropertyContribution').find('a').each(function () {
        var aContent = $(this).html();
        for (var i = 0; i < propertyContributionArray.length; i++) {
            for (var key in propertyContributionArray[i]) {
                if (aContent == key) {
                    for (var k = 0; k < propertyContributionArray[i][key].length; k++) {
                        for (var item in propertyContributionArray[i][key][k]) {
                            $(this).attr(item, propertyContributionArray[i][key][k][item]);
                        }
                    }
                }
            }

        }
    });

    //查看业主事件
    $("#lstOwnerMobile").hide();
    $("#btnOwnerMobile").toggle(function () {
        var urlNum = $("#PropertyKeyIdhid").val();
        $(this).find("i").css("background-position", "-324px -24px");
        $.AjaxAgency("/Property/trustors-obtain", { 'keyId': urlNum }, function (data) {
            $("#lstOwnerMobile").show();
            $("#lstOwnerMobile").html(data);
            $("#dvTapeMobile").show();
            var value = "<span class='ml5'>虚拟号短号拨打已改成一键拨号，请点击</span><i class='icon-phone'></i>";
            $("#dvTapeMobile").html(value);
        });
    }, function () {
        $("#lstOwnerMobile").hide();
        $("#lstOwnerMobile").html('');
        $("#dvTapeMobile").hide();
        $(this).find("i").css("background-position", "-324px -35px");
    });
    //临时
    $(".view-owner-set").click(function () {
        var urlNum = $("#PropertyKeyIdhid").val();
        $.ajax({
            type: 'post',
            url: '/Property/trustors-obtain',
            data: { 'keyId': urlNum },
            success: function (data) {
                $("#lstOwnerMobile").show();
                $("#lstOwnerMobile").html(data);
            }
        });
        $(".owner-sets-box").hide();
    });

    //操作面板
    $("#operatePanelBox").hover(function () {
        $(this).find("ul").show();
        $(this).find("i").addClass("gray-down-arrow-on");

        var url = "/property/user-status-operate-obtain-ajax";

        var keyId = $("#PropertyKeyIdhid").val();
        var reqData = {
            "keyId": keyId
        };

        $.AjaxAgency(url, reqData, function (data) {
            $("#btnSetCancelFavorite").html(data.IsFavorite ? "取消收藏" : "收藏");
            $("#btnSetCancelRecommend").html(data.IsRecommend ? "取消推荐" : "推荐");
            $("#btnSetCancelNoCall").html(data.IsNoCall ? "取消免扰设置" : "免扰设置");
            $("#btnSetCancelTogetherTakeSee").html(data.IsTogetherTakeSee ? "取消集中带看房" : "设置集中带看房");
        });
    }, function () {
        $(this).find("ul").hide();
        $(this).find("i").removeClass("gray-down-arrow-on");
    });

    //工具面板
    $("#toolsPanelBox").unbind("hover");
    $("#toolsPanelBox").hover(function () {
        $(this).find("ul").show();
        $(this).find("i").addClass("gray-down-arrow-on");
    }, function () {
        $(this).find("ul").hide();
        $(this).find("i").removeClass("gray-down-arrow-on");
    })

    //收藏、取消收藏
    $("#btnSetCancelFavorite").bind("click", function () {
        var url;
        var keyId = $("#PropertyKeyIdhid").val();
        var reqData = {
            "propertyid": keyId
        };

        if ($(this).html() == "收藏") {
            url = "/property/Favorite";
            $.AjaxAgency(url, reqData, function (data) {
                if (data == "OK") {
                    $.OKDialogAgency('<div class="tc">收藏成功！</div>', '提示', function () {
                        $("#btnSetCancelFavorite").html("取消收藏");
                    })
                } else {
                    $.OKDialogAgency('<div class="tc">收藏失败！</div>');
                }
            });
        } else if ($(this).html() == "取消收藏") {
            url = "/property/favorite-cancel-ajax";
            $.AjaxAgency(url, reqData, function (data) {
                if (data == "OK") {
                    $.OKDialogAgency('<div class="tc">取消收藏成功！</div>', '提示', function () {
                        $("#btnSetfavorite-cancel-ajax").html("收藏");
                    })
                } else {
                    $.OKDialogAgency('<div class="tc">取消收藏失败！</div>');
                }
            });
        }
    });

    //推荐、取消推荐
    $("#btnSetCancelRecommend").bind("click", function () {
        var url = "/property/property-single-recommend-cancel-ajax";

        var keyId = $("#PropertyKeyIdhid").val();
        var type = "";
        if ($(this).html() == "推荐") {
            type = "recommend";
        } else if ($(this).html() == "取消推荐") {
            type = "cannel";
        }

        var reqData = {
            "keyId": keyId,
            "type": type
        };
        var tempPromptValue = $(this).html();
        $.dialog({
            lock: true,
            background: "#808080",
            opacity: 0.87,
            content: '<div class="tc">您确定要' + tempPromptValue + '吗？</div>',
            cancel: function () { },
            ok: function () {
                $.AjaxAgency(url, reqData, function (data) {
                    if (data == "ok") {
                        if ($("#btnSetCancelRecommend").html() == "推荐") {
                            $.dialog({
                                lock: true,
                                background: "#808080",
                                opacity: 0.87,
                                content: '<div class="tc">推荐成功！</div>',
                                cancel: function () { }
                            }).time(2);
                            $("#btnSetCancelRecommend").html("取消推荐");
                            window.location.reload();
                        }
                        else if ($("#btnSetCancelRecommend").html() == "取消推荐") {
                            $.dialog({
                                lock: true,
                                background: "#808080",
                                opacity: 0.87,
                                content: '<div class="tc">取消推荐成功！</div>',
                                cancel: function () { }
                            }).time(2);

                            $("#btnSetCancelRecommend").html("推荐");
                            window.location.reload();
                        }
                    }
                    else {
                        $.dialog({
                            lock: true,
                            background: "#808080",
                            opacity: 0.87,
                            content: data,
                            cancel: function () { }
                        });
                    }
                });
            }
        });

    });

    //设置、取消免扰设置
    $("#btnSetCancelNoCall").bind("click", function () {
        if ($(this).html() == "免扰设置") {
            NoCall.SetNoCall(this);
        } else if ($(this).html() == "取消免扰设置") {
            NoCall.CancelNoCall(this);
        }
    });

    //设置、取消集中带看房
    $("#btnSetCancelTogetherTakeSee").bind("click", function () {
        if ($(this).html() == "设置集中带看房") {
            TogetherTakeSee.SetTogetherTakeSee(this);
        } else if ($(this).html() == "取消集中带看房") {
            TogetherTakeSee.CancelTogetherTakeSee(this);
        }
    });

    function changeStatusSuccess(e) {
        $("#currentStatusStr").html("[" + e + "]");
    }


    //手动结盘
    $("#btnPropertyManualOver").bind("click", function () {
        var reqData = {
            "propertyKeyId": $(".btnValues").attr('keyid')
        };

        //判断房源状态是否为预定
        $.AjaxAgency('/property/GetPropertyStatus', reqData, function (data) {
            if (data.Flag) {
                $.dialog({
                    id: "ManualOver",
                    title: "手工结盘",
                    lock: true,
                    width: 650,
                    content: $("#divPropertyManualOver").html()
                });
                $("input[name=txtPric]").attr("maxlength", 6);

                $("div #btn_ManualOver").click(function () {
                    proertyFollow.ManualOverSubmit();
                });

                agencyVerify.notNullInput("#propertyManualOver", "input[name=ownerName]:visible", true, "blur");
                agencyVerify.mobileInput("#propertyManualOver", "input[name=txtMobile]:visible", true, "blur");
                agencyVerify.notNullInput("#propertyManualOver", "input[name=txtPric]:visible", true, "blur");
                agencyVerify.notdefaultSelect("#propertyManualOver", "#divOwnerInfo :visible[name=GenderKeyId]", -1, "必须选择联系人称谓！", true);
                //0-9数字验证
                agencyVerify.greaterThanEqualZero("#artTelphone1,#artTelphone2,#artTelphone3", true);
                $("input[name=txtMobile]:visible").change(function () {
                    chooseMobileOrTelPhone();
                    $(this).blur();
                });
                $("#artTelphone2").blur(function () {
                    chooseMobileOrTelPhone();
                });

                //表单提交事件
                $("#propertyManualOver").bind("submit", function () {
                    return SubmitOnBegin();
                });
            }
            else {
                $.OKDialogAgency('<div class="tc">' + data.ErrorMsg + '</div>');
            }
        });

    });


    proertyFollow.ManualOverSubmit = function () {
        chooseMobileOrTelPhone();
        if ($("#propertyManualOver").find(".wrong:visible").length > 0) {
            return false;
        }
    }

    //委托备案
    $('#btnEntrustKeepOnRecord').click(function () {
        $.dialog({
            id: "turnEntrust",
            title: "委托备案",
            lock: true,
            content: $("#EntrustKeepOnRecord").html()
        });
        PopupWindowRecord.makeUploadBtn();
        EmployeePrompt.getDepartAndEmployeeByInput(null, "hidDepartmentKeyId", "btnRegisterPerson", "hidUserId", false, "private", 1, "请选择业务员", null, null, true);
    });

    //状态修改    
    $('#btnPropertyStatusModifyDetail').click(function () {
        objCheck = $('input.btnValues');
        if (!ListAndDetailRight.CheckStatusRight(objCheck)) {
            return false;
        }
        $.dialog({
            id: "turnStatus",
            title: "状态修改",
            lock: true,
            content: $("#CHANGESTATUSdiv").html()
        });
        $("#txtContractorName").blur(function () {
            if ($("#txtContractorName").val() == "") {
                $("#txtContractorName").addClass("checkError");
                if ($("#txtContractorName").next(".wrong").length <= 0) {
                    $("#txtContractorName").after(agencyVerify.greatErrorHtml($("#txtContractorName"), '此项必填'));
                }
                return false;
            } else {
                $("#txtContractorName").next(".wrong").remove();
                $("#txtContractorName").removeClass("checkError");
                $("#btn_upstatus").removeAttr("disabled");
            }
        });
        
        $.inputStatistics("CHANGESTATUSdivTextarea", 200);

        $("#TargetPropertyStatusKeyId2").empty();
        $("#hidPropertyKeyId").val(objCheck.attr("keyid"));
        EmployeePrompt.getDepartAndEmployeeByInput(null, null, "txtContractorName", "hidContractorKeyId", false, "private", 1, null, null, "请选择成交人");
        agencyVerify.NeedSmartTips("#addFollowForm", "#txtContractorName", "#hidContractorKeyId", "成交人必需从智能提示中选择", false);
        $("#CHANGESTATUSdivTextarea").blur(function () {
            if ($("#CHANGESTATUSdivTextarea").val() == "") {
            } else {
                $("#CHANGESTATUSdivTextarea").removeClass("checkError");
                $("#btn_upstatus").removeAttr("disabled");
            }
        });
        proertyFollow.statusOptions(objCheck.attr("status"), "#TargetPropertyStatusKeyId2");
        agencyVerify.notNullInput("div.aui_content #addFollowForm", "div.aui_content textarea[notnull=notNull]", false, "blur");
        agencyVerify.notNullInput("div.aui_content #addFollowForm", "div.aui_content input[notnull=notNull]", false, "blur");
        propertyStatus("状态");
        $("#expertTransactionTypeKeyId2 label").click(function () {
            $("#trustorDelayShow2 input[name=TrustorDelay]").val(0);
            $("#trustorDelayShow2 input[name=TrustorDelay]").attr("checked", false);
        });
    });

    //发布房源
    $("#btnReleasePropertyDetail").unbind('click');
    $("#btnReleasePropertyDetail").click(function () {
        var objCheck;
        objCheck = $('input.btnValues');
        var IsRegisterTrusts;
        var offSwitch = 0;//业主委托备案开关，默认关闭
        var trustAudit = 0;//业主委托备案审核放盘开关，默认关闭
        var data = dataBind.getRealDataByType(98);
        if (data.length > 0) {
            for (var i = 0; i < data.length ; i++) {
                if (data[i].ItemText == "业主委托开关") {
                    if (data[i].ExtendAttr == "1") {
                        IsRegisterTrusts = true;
                        offSwitch = 1;
                    }
                }
                else if (data[i].ItemText == "委托书必须审核通过才能放盘") {
                     if (data[i].ExtendAttr == "1") {
                        trustAudit = 1;
                    }
                }
            }
        }
        var HasRegisterTrusts = objCheck.attr('HasRegisterTrusts');
        //业主委托审核状态
        var RegisterTrustAudit = objCheck.attr('RegisterTrustAudit');
        //如果业主委托备案开关开启
        if (offSwitch == "1") {
            if (IsRegisterTrusts == true) {
                if (HasRegisterTrusts == 0) {
                    $.OKDialogAgency('<div class="tc">此房源为非委托房源，禁止发布房源！</div>');
                    return false;
                }
                if (RegisterTrustAudit != "1" && trustAudit == "1") {
                    $.OKDialogAgency('<div class="tc">房源委托必须为审核通过才能发布房源！</div>');
                    return false;
                }
            }
        }
        var reqData = {
            "propertyKeyId": $(".btnValues").attr('keyid')
        };
        $.AjaxAgency('/property/property-post', reqData, function (data) {
            if (data.Flag) {
                if (data.Result != null && data.Result.ErrorNumber == '0') {
                    window.open(data.Result.RedirectUrl);
                } else {
                    $.OKDialogAgency('<div class="tc">' + data.Result.ErrorDescription + '</div>');
                }
            }
            else {
                $.OKDialogAgency('<div class="tc">' + data.ErrorMsg + '</div>');
            }
        });
    });

    $("#btnTurnShiefRight").unbind('click');
    $("#btnTurnShiefRight").bind("click", function () {
        //要判断一下是否有转公盘或转个人权限
        var objCheck = $('input.btnValues');
        var turnpublic = ListAndDetailRight.CheckTrunPRight(objCheck);
        var trunprivate = ListAndDetailRight.CheckTrunRight(objCheck);
        if ((!trunprivate) && (!turnpublic)) {
            $.OKDialogAgency('<div class="tc">你没有转该房源的权限！</div>');
            return false;
        }
        $.dialog({
            id: "turnShiefRight",
            title: "转盘",
            lock: true,
            content: $("#turnShiefRight").html()
        });

        $.inputStatistics("TRUN2divTextarea", 200);
        //初始化转部门和业务员方法
        //要判断一下转盘的范围是公盘,个人,还是都有权限
        var temrang = "";
        if (turnpublic && trunprivate) {
            temrang = "all";
        }
        else if (turnpublic) {
            temrang = "public";
        }
        else if (trunprivate) {
            temrang = "private";
        }
        $("#txtTurnEmployeeName").blur(function () {
            if ($("#txtTurnEmployeeName").val() == "") {
                $("#txtTurnEmployeeName").addClass("checkError");
                if ($("#txtTurnEmployeeName").next(".wrong").length <= 0) {
                    $("#txtTurnEmployeeName").after(agencyVerify.greatErrorHtml($("#txtTurnEmployeeName"), '此项必填'));
                }
                return false;
            } else {
                $("#txtTurnEmployeeName").next(".wrong").remove();
                $("#txtTurnEmployeeName").removeClass("checkError");
                $("#btn_upstatus").removeAttr("disabled");
            }
        });
        $("#txtContractorName").blur(function () {
            if ($("#txtContractorName").val() == "") {
                $("#txtContractorName").addClass("checkError");
                if ($("#txtContractorName").next(".wrong").length <= 0) {
                    $("#txtContractorName").after(agencyVerify.greatErrorHtml($("#txtContractorName"), '此项必填'));
                }
                return false;
            } else {
                $("#txtContractorName").next(".wrong").remove();
                $("#txtContractorName").removeClass("checkError");
                $("#btn_upstatus").removeAttr("disabled");
            }
        });
        
        $("#CHANGESTATUSdivTextarea").blur(function () {
            if ($("#CHANGESTATUSdivTextarea").val() == "") {
            } else {
                $("#CHANGESTATUSdivTextarea").removeClass("checkError");
                $("#btn_upstatus").removeAttr("disabled");
            }
        });

        EmployeePrompt.getDepartAndEmployeeByInput("txtTurnDepartName", "hidTurnDepartKeyId", "txtTurnEmployeeName", "hidTurnEmployeeKeyId", false, temrang, 1, "", "", true);
        agencyVerify.NeedSmartTips("#addFollowForm", "#txtTurnDepartName", "#hidTurnDepartKeyId", "部门必需从智能提示中选择", false);
        agencyVerify.NeedSmartTips("#addFollowForm", "#txtTurnEmployeeName", "#hidTurnEmployeeKeyId", "业务员必需从智能提示中选择", false);

        //proertyFollow.statusOptions(objCheck.attr("status"), "#TargetPropertyStatusKeyId1");
        EmployeePrompt.getDepartAndEmployeeByInput(null, null, "txtContractorName", "hidContractorKeyId", false, "private", 1, "请选择成交人", null, null, null, null, null);
        agencyVerify.NeedSmartTips("#addFollowForm", "#txtContractorName", "#hidContractorKeyId", "成交人必需从智能提示中选择", false);

        $("#TargetPropertyStatusKeyId1").empty().append('<option value="-1">保持现状</option>');
        //判断更改状态的本人、本部、全部权限
        var roleRight = $("#hidPermissions").val();
        var myDepartments = $("#hidMyDepartments").val();
        var operator = $("#hidOperatorID").val();
        var userid = objCheck.attr("userid");
        var departmentid = objCheck.attr("departmentid");
        if (roleRight.indexOf("Property.PropertyStatus.Modify-MySelf") > -1 && userid == operator) {
            proertyFollow.statusOptions(objCheck.attr("status"), "#TargetPropertyStatusKeyId1");
        } else if (roleRight.indexOf("Property.PropertyStatus.Modify-MyDepartment") > -1 && myDepartments.indexOf(departmentid) > -1) {
            proertyFollow.statusOptions(objCheck.attr("status"), "#TargetPropertyStatusKeyId1");
        } else if (roleRight.indexOf("Property.PropertyStatus.Modify-All") > -1) {
            proertyFollow.statusOptions(objCheck.attr("status"), "#TargetPropertyStatusKeyId1");
        } else {
            $("#TargetPropertyStatusKeyId1").empty().append('<option value="-1">保持现状</option>');
        }
        $("#hidPropertyKeyId").val(objCheck.attr("keyid"));
        
        agencyVerify.notNullInput("div.aui_content #addFollowForm", "div.aui_content input[notnull=notNull]", false, "blur");
        
       propertyStatus("转盘");
    });
    //业绩声明
    $.AjaxAgency("performance-list?edit=" + $("#hidHaveEditPerformance").val(), { keyid: $("#PropertyKeyIdhid").val() }, function (data) {
        $("#PerformanceDiv").html(data);
    });

    //发布房源临时弹框
    $("#btnReleasePropertyDetail1").on("click", function () {
        $.dialog({
            id: "btnReleasePropertyDetail1",
            lock: true,
            title: "友情提示",
            width: 300,
            height: 150,
            content: '<center style="font-size:25px;">暂未开放...</center>'
        });
    });
});
function getTitles() {
    //, "历史记录"
    var titles = [];
    if ($("#hidIsMyreferral").val() != "1") {
        if (ListAndDetailRight.CheckRight($("#hidPropertyChiefDepartmentKeyId")[0], "Property.Follow.Search")) {
            titles.push("房源跟进");
        }
        titles.push("图片");
        if (ListAndDetailRight.CheckRight($("#hidPropertyChiefDepartmentKeyId")[0], "Property.RealSurvey.Search")) {
            titles.push("实勘");
        }
        if (ListAndDetailRight.CheckRight($("#hidPropertyChiefDepartmentKeyId")[0], "Property.Key.Search")) {
            titles.push("钥匙");
        }
        //反签不受权限控制，这是需求
        titles.push("签约");

        titles.push("地图");
        titles.push("叫价记录");
        if (ListAndDetailRight.CheckRight($("#hidPropertyChiefDepartmentKeyId")[0], "Property.Property.SearchLog")) {
            titles.push("操作日志");
        }
    }
    if (ListAndDetailRight.CheckRight($("#hidPropertyChiefDepartmentKeyId")[0], "Property.History.Search") || window.location.href.indexOf("myreferral") > -1) {
        titles.push("历史记录");
    }
    if ($("#hidPermissions").val().indexOf("Property.CallLog.Modify-None") < 0) {
        titles.push("通话记录");
    }


    return titles;
};

function getTabUrl(tabname) {
    if (tabname == "房源跟进") {

        var urlParamters = $('#parPropertyKeyId').val() + '&' + $('#parPropertyNo').val() + '&' + $('#parSalePrice').val() + '&' + $('#parSquare').val() + '&' + $('#parEstateName').val() + '&' + $('#parPropertyChiefKeyId').val() + '&' + $('#parPropertyStatus').val();
        urlParamters += "&delFollowDeparment=" + $("#hidDelFollowDeparment").val() + "&haveTopFollowRight=" + $("#hidHaveTopFollowRight").val() + "&haveAddFollowRight=" + $("#hidHaveAddFollowRight").val() + "&haveConfirmFollowRight=" + $("#hidHaveConfirmFollowRight").val();
        var tempUrl = window.location.href;
        if (tempUrl.indexOf("#maodian&") != -1) {
            window.location.href = window.location.href.split("#maodian&")[0];
        }

        return encodeURI("/property/proerty-detail-follow?" + urlParamters);
    }
    if (tabname == "图片") {
        return "/property/property-detail-photos-obtain?" + $('#parPropertyKeyId').val() + "&v=" + Math.random();
    }
    if (tabname == "实勘") {
        return "/property/property-real-survey-obtain?" + $('#parPropertyKeyId').val() + "&v=" + Math.random();
    }
    if (tabname == "钥匙") {
        var url = "/property/property-key-obatin?" + $('#parPropertyKeyId').val() + '&keyContent=' + escape($('#keyContent').val());
        url += "&HaveAddKeyRight=" + $("#hidHaveAddKeyRight").val();
        return url;
    }
    if (tabname == "签约") {
        return "/property/property-only-trust-obtain?" + $('#parPropertyKeyId').val() + "&HaveAddOnlyTrustRight=" + $("#hidHaveAddOnlyTrustRight").val();
    }
    if (tabname == "地图") {
        return "/property/baidu-map?a=1";
    }
    if (tabname == "历史记录") {
        return "/property/property-history-record?" + $('#parPropertyKeyId').val();
    }
    if (tabname == "叫价记录") {
        return "/property/property-price-change-record?IsSwitch=false&" + $('#parPropertyKeyId').val();
    }
    if (tabname == "操作日志") {
        return "property-log?" + $('#parPropertyKeyId').val();
    }
    if (tabname == "通话记录") {
        return "/property/property-call-record?" + $('#parPropertyKeyId').val();
    }
    return "/Common/Error404?a=1";
};

function getData(tabname) {
    return [{ name: "key", value: tabname }];
};
function addElementAttr(obj, jsonObj) {
    for (var key in jsonObj) {
        $.OKDialogAgency('<div class="tc">' + key + '</div>', '提示', function () {
            $(obj).attr(key, jsonObj[key]);
        });
    }
}
//转盘成功
propertyDetails.TurnSucces = function (data) {
    if (data == "ok") {
        $.OKDialogAgency('<div class="tc">转盘成功</div>', '提示', function () {
            //art.dialog.get("turnShiefRight").close();
            $("#btnSubmit").click();
        });
    }
    else {
        $.OKDialogAgency('<div class="tc">' + data + '</div>');

    }
    art.dialog.get("turnShiefRight").close();
    $("#btnSubmit").click();
}
//修改状态成功
propertyDetails.TurnStatusSucces = function (data) {
    if (data == "ok") {
        $.OKDialogAgency('<div class="tc">状态更改成功</div>', '提示', function () {
            window.location.reload();
        });
    } else {
        $.OKDialogAgency('<div class="tc">' + data + '</div>');
    }
    art.dialog.get("turnStatus").close();
}
//业绩声明相关逻辑
propertyDetails.showPerformanceDiv = function (item) {
    $.dialog({
        id: "showPerformancedialog",
        lock: true,
        title: "业绩声明",
        background: "#808080",
        opacity: 0.87,
        content: $("#PerformanceTmp").html()
    });
    dataBind.bindOption(84, "#cmbSysParameterItemCode", true);
    //agencyVerify.nonnegativeInput("#Rate", false);
    $("#PerformanceUserName").bind("change", function () {
        $("#PerformanceUserKeyId").val("");
    });
    $("#cmbSysParameterItemCode").change(function () {
        var code = $(this).val();
        if (code == "10" || code == "15" || code == "20" || code == "30" || code == "80" || code == "100") {
            $("#RelatedPersonLink").show();
        }
        else {
            $("#RelatedPersonLink").hide();
        }
    });
    $("#PerformanceUserName").autocomplete(function () {
        return "/account/GetUserListBy?name=" + escape($("#PerformanceUserName").val());
    }, {
        width: 200,
        max: 12,
        selectFirst: false,
        formatItem: function (row) {
            return row.UserName + "(" + row.EmployeeNo + ")<span style='float:right'>" + row.DepartmentName + "</span>";
        },
        formatResult: function (row) {
            return row.UserName;
        }
    }).result(function (a, b) {
        $("#PerformanceUserKeyId").val(b.UserKeyId);
        $("#PerformanceDepartmentKeyId").val(b.DepartmentKeyId);
    });
    var addeditUrl = "";
    var perKeyId = "";
    if (item) {
        $("#cmbSysParameterItemCode").val($(item).attr("SysParameterItemCode"));
        $("#PerformanceUserName").val($(item).attr("UserName"));
        $("#Rate").val($(item).attr("Rate"));
        $("#PerformanceUserKeyId").val($(item).attr("UserKeyId"));
        $("#PerformanceDepartmentKeyId").val($(item).attr("DepartmentKeyId"));
        addeditUrl = "performance-modify-ajax";
        perKeyId = $(item).attr("keyid");
        $("#cmbSysParameterItemCode").change();
    }
    else {
        addeditUrl = "CreatePerformance";
    }
    $("#btnCreatePerformance").bind("click", function () {
        if ($("#cmbSysParameterItemCode").val() == "全部") {
            $.OKDialogAgency('<div class="tc">请选择分配说明</div>');
            $("#cmbSysParameterItemCode").focus();
            return;
        }
        if (!$("#PerformanceUserKeyId").val()) {
            $.OKDialogAgency('<div class="tc">请从下拉选择框或相关人中选择分成人</div>');
            $("#PerformanceUserName").focus();
            return;
        }
        //if ($("#Rate").val() == "") {
        //    $.OKDialogAgency('<div class="tc">请填写比例</div>');
        //    $("#Rate").focus();
        //    return;
        //}
        //if (Number($("#Rate").val()) <= 0) {
        //    $.OKDialogAgency('<div class="tc">比例必须大于零</div>');
        //    $("#Rate").focus();
        //    return;
        //}
        //if ($("#Rate").val() > 100) {
        //    $.OKDialogAgency('<div class="tc">比例不能大于100</div>');
        //    $("#Rate").focus();
        //    return;
        //}
        $.AjaxAgency(addeditUrl, { KeyId: perKeyId, 'PerformanceUserKeyId': $("#PerformanceUserKeyId").val(), 'PerformanceUserName': $("#PerformanceUserName").val(), PerformanceDepartmentKeyId: $("#PerformanceDepartmentKeyId").val(), Rate: $("#Rate").val(), PropertyKeyId: $("#PropertyKeyIdhid").val(), SysParameterItemCode: $("#cmbSysParameterItemCode").val(), SysParameterItemName: $("#cmbSysParameterItemCode option:selected").text() }, function (data) {
            if (data == "ok") {
                if (addeditUrl == "CreatePerformance") {
                    $.OKDialogAgency('<div class="tc">添加成功</div>', '提示', function () {
                        art.dialog.get("showPerformancedialog").close();
                        $.AjaxAgency("performance-list?edit=" + $("#hidHaveEditPerformance").val(), { keyid: $("#PropertyKeyIdhid").val() }, function (data) {
                            $("#PerformanceDiv").html(data);
                        });
                    });
                }
                else {
                    $.OKDialogAgency('<div class="tc">编辑成功</div>', '提示', function () {
                        art.dialog.get("showPerformancedialog").close();
                        $.AjaxAgency("performance-list?edit=" + $("#hidHaveEditPerformance").val(), { keyid: $("#PropertyKeyIdhid").val() }, function (data) {
                            $("#PerformanceDiv").html(data);
                        });
                    });
                }
            }
            else {
                $.OKDialogAgency('<div class="tc">' + data + '</div>');
            }
        });
    });

}
propertyDetails.showRelatedPerson = function (a) {
    $(a).attr("disabled", "disabled");
    var code = $("#cmbSysParameterItemCode").val();
    var pid = $("#PropertyKeyIdhid").val();
    var contentRelate;
    $.AjaxAgency("performance-similar-user-ajax", { 'SysParameterItemCode': code, 'PropertyKeyId': pid }, function (data) {
        var str = "";
        for (var i = 0; i < data.length; i++) {
            str += '<li class="cp" userid="' + data[i].UserKeyId + '" depart="' + data[i].DepartmentKeyId + '" onclick="propertyDetails.writeRelatedPerson(this)">' + data[i].UserName + '(' + data[i].DepartmentName + ')</li>';
        }
        if (str) {
            contentRelate = "<ul>" + str + "</ul>";
        }
        else {
            contentRelate = "没有相关人";
        }
        $(a).removeAttr("disabled");
        $.dialog({
            id: "showRelatedPersondialog",
            lock: true,
            title: "选择相关人",
            background: "#808080",
            opacity: 0.87,
            width: 300,
            content: contentRelate
        });
    });
}
propertyDetails.writeRelatedPerson = function (a) {
    $("#PerformanceDepartmentKeyId").val($(a).attr("depart"));
    $("#PerformanceUserName").val($(a).text().split('(')[0]);
    $("#PerformanceUserKeyId").val($(a).attr("userid"));
    art.dialog.get("showRelatedPersondialog").close();
}
propertyDetails.DelPerformance = function (a) {

    // if (confirm("确定删除该条记录？")) {
    $.OKCancelDialogAgency('<div class="tc">您确定删除' + $(a).attr("pname") + '的业绩声明？</div>', '删除业绩声明', true, function () {
        $.AjaxAgency("performance-delete-ajax", { key: $(a).attr("keyid") }, function (data) {
            if (data == "ok") {
                $(a).parent().parent().remove();
                $.OKDialogAgency('<div class="tc">删除成功！</div>');
            }
            else {
                $.OKDialogAgency('<div class="tc">' + data + '</div>');
            }
        });
    });
}


function chooseMobileOrTelPhone() {

    var msg = '业主手机电话至少填一个';
    if ($("input[name=txtMobile]:visible").val() == "" && $("input[name=telphone2]:visible").val() == "") {
        $("input[name=txtMobile]:visible").focus();
        $("input[name=txtMobile]:visible").addClass("checkError");
        var wrongspan = $("input[name=txtMobile]:visible").next();
        if (wrongspan.attr("class") != "wrong" ||
            (wrongspan.attr("class") == "wrong" && wrongspan.text() == "")) {
            var temspan = $("input[name=txtMobile]:visible").after(agencyVerify.greatErrorHtml($("input[name=txtMobile]:visible").get(0), msg));
        }
    }
    else {
        var wrongspan = $("input[name=txtMobile]:visible").next();
        if (wrongspan.length != 0) {
            var textMsg = wrongspan.get(0).innerText;
            if (wrongspan.attr("class") == "wrong" && textMsg == msg) {

                wrongspan.remove();
                $("input[name=txtMobile]:visible").removeClass("checkError");
                //这一点很重要,当一个验证从不通过到通过时,需要重新验证所有在此元素上的验证事件
                $("input[name=txtMobile]:visible").change();
            }
        }
    }
}

function SubmitOnBegin() {
    if ($("#propertyManualOver").find(".wrong:visible").length > 0) {
        return false;
    }

    var propertyType = $("#propertyTrustType").val();    //房源交易类型
    var transactionType = $("input[name=TransactionType]:checked").val();       //成交类型
    // type: 1=出售  2=出租  3=租售
    if (propertyType != transactionType) {
        if (transactionType == 1 && propertyType == 2) {
            $.OKDialogAgency('<div class="tc">您选择是售成交，而房源当前交易类型为租</div>');
            return false;
        }
        else if (transactionType == 2 && propertyType == 1) {
            $.OKDialogAgency('<div class="tc">您选择的是租成交，而房源的交易类型不是租</div>');
            return false;
        }
        else if (propertyType==0) {
            return false;
        }
    }
    

    $.OKCancelDialogAgency('<div class="tc">您确定手工结盘？</div>', '手动结盘', true, function () {

        var url = "/Property/property-manualOver";
        var displayTelphone = "";
        if ($("#artTelphone1").val() != null && $("#artTelphone1").val() != "") {
            displayTelphone += $("#artTelphone1").val() + "-";
        }
        if ($("#artTelphone2").val() != null && $("#artTelphone2").val() != "") {
            displayTelphone += $("#artTelphone2").val();
        }

        if ($("#artTelphone3").val() != null && $("#artTelphone3").val() != "") {
            displayTelphone += "-" + $("#artTelphone3").val();
        }

        var reqData = {
            "PropertyKeyId": $("#hidPropertyKeyId").val(),
            "ownerName": $("#txtOwnerName").val(),
            "TransactionType": $("input[name=TransactionType]:checked").val(),
            "telphone": displayTelphone,
            "GenderKeyId": $("#idGenderKeyId").val(),
            "txtMobile": $("input[name=txtMobile]").val(),
            "txtPric": $("input[name=txtPric]").val()
        };
        $.AjaxAgency(url, reqData, function (data) {
            if (data.Flag) {
                $.OKDialogAgency('<div class="tc">手动结盘成功</div>');
            }
            else {
                $.OKDialogAgency('<div class="tc">' + data.ErrorMsg + '</div>');
            }
            art.dialog.get("ManualOver").close();
        });
    });

    return false;
}

//预约摄影师相关逻辑
propertyDetails.GetPhotographer = function () {
    var reqData = {
        "departmentKeyId": $("#parDeptKeyId").val()
    }
    $.AjaxAgency("/Property/department-photographer-auto-obtain-ajax", reqData, function (data) {
        if (data.Flag) {
            for (var i = 0; i < data.PhotographerList.length; i++) {
                $("#PhotographerSelect").append("<option value='" + data.PhotographerList[i].PhotoGrapherKeyId + "'>" + data.PhotographerList[i].PhotoGrapherName + "</option>");
            }
        } else {
            $.OKDialogAgency('<div class="tc">获取部门摄影师信息失败！</div>');
        }
    });
}

propertyDetails.ReservePhotographer = function () {
    var reqData = {
        "ShootDate": $("#btnPopupTrustsTime").val(),
        "ShootClock": $("#clockNum").val(),
        "PhotoGrapherUserKeyId": $("#PhotographerSelect").val(),
        "Remark": $("#ReservePhotographerTextarea").val()
    }

    $.AjaxAgency("/Property/Create-Reserve-Photographer", reqData, function () {

    });
}

